package main

import(
	"log"
	"os"
	"time"
	"net/http"
	"github.com/bugfan/logrus"    	
	_ "github.com/bugfan/logrus/hooks/file"    	
	"github.com/gorilla/websocket"
	"errors"
	"strconv"
)
var(
	upgrader = websocket.Upgrader{}
	data_gas_fan  		string="{}"
	data_person_posi  	string="{}"
	data_voice_broad  	string="{}"
	data_trans_rise  	string="{}"
	data_temp_moni  	string="{}"	

	blockData =make(chan string,1)
)

func gas_fan(w http.ResponseWriter,r *http.Request){
	r.Header.Del("Origin")
	c,err:=upgrader.Upgrade(w,r,nil)
	logrus.Info("--> 连接了一个:",err,c.RemoteAddr())
	defer  func(){
		logrus.Info("<-- 退了一个:",err,c.RemoteAddr())
		c.Close()
	}()
	for {
		if data,ok := <- blockData;ok{
			if err:=c.WriteMessage(1,[]byte(data_gas_fan));err!=nil{
				logrus.Println(" err退出:",err)
				break
			}else{
				logrus.Println(" 消息推送完成~",data)
			}
		}
	}
}
func upload(w http.ResponseWriter,r *http.Request){
	if r.Header.Get("leaniot")!="leaniot"{
		w.Write([]byte(`{"status":false,"msg":"fail : error key"}`))
		return
	}
	/*
	*	处理数据
	*/
	w.Write([]byte(`{"status":true,"msg":"success"}`))
}
func main(){
	// ws read --> _,bs,err:=c.ReadMessage()
	http.HandleFunc("/ws/gas_fan", gas_fan)

	http.HandleFunc("/api/upload", upload)	
	go checkBlock()
	run()
}
func checkBlock(){
	for {
		time.Sleep(4e9)
		blockData <- "zxy"
		logrus.Info("z")
	}
}
func run() {
	port := ""
	if len(os.Args) < 3 {
		log.Fatal(errors.New("缺少服务器启动参数"))
		return
	}
	for i, v := range os.Args {
		if i == 1 {
			switch v {
			case "-ws":
				port = os.Args[2]
				if !isPort(port) {
					log.Fatal(errors.New("port错误"))
				}
			default:
				log.Fatal(errors.New("protocol未指定"))
			}
		}
	}
	logrus.Println("--启动websocket服务--")	
	log.Fatal(http.ListenAndServe(":"+port, nil))
}
func isPort(v string) bool {
	_, err := strconv.Atoi(v)
	if err != nil {
		return false
	}
	return true
}